package com.kinglone.back.init.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import com.kinglone.back.blog.model.Blog;
import com.kinglone.back.blog.service.BlogService;
import com.kinglone.back.blogType.model.BlogType;
import com.kinglone.back.blogType.service.BlogTypeService;
import com.kinglone.back.link.model.Link;
import com.kinglone.back.link.service.LinkService;
import com.kinglone.back.music.model.Music;
import com.kinglone.back.music.service.MusicService;

/**
 * 初始化组件 把博主信息 根据博客类别分类信息 根据日期归档分类信息 存放到application中，用以提供页面请求性能
 * @author Administrator
 *
 */
@Component
public class InitComponent implements ServletContextListener,ApplicationContextAware {

	private static ApplicationContext applicationContext;
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext)throws BeansException {
		
		this.applicationContext = applicationContext;
	}

	@Override
	public void contextInitialized(ServletContextEvent servletContextEvent) {
		
		ServletContext application=servletContextEvent.getServletContext();
		
		BlogTypeService blogTypeService=(BlogTypeService) applicationContext.getBean("blogTypeService");
		List<BlogType> blogTypeCountList=blogTypeService.countList(); // 查询博客类别以及博客的数量
		application.setAttribute("blogTypeCountList", blogTypeCountList);
		
		BlogService blogService =(BlogService) applicationContext.getBean("blogService");
		List<Blog> blogCountList = blogService.countList(); // 根据日期分组查询博客
		application.setAttribute("blogCountList", blogCountList);
		
		LinkService linkService =(LinkService) applicationContext.getBean("linkService");
		List<Link> linkList= linkService.list(null);//查询友情链接
		application.setAttribute("linkList", linkList);
		
		MusicService musicService =(MusicService) applicationContext.getBean("musicService");
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("ifUse", 0);
		List<Music> musicList= musicService.list(map);//查询音乐
		JSONArray jsonArray = new JSONArray();
		for (int i = 0;i<musicList.size();i++){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("url",musicList.get(i).getMusicUrl());
            jsonObject.put("name",musicList.get(i).getMusicName());
            jsonArray.add(jsonObject);
        }
		application.setAttribute("MusicData", jsonArray);
	}
	
	@Override
	public void contextDestroyed(ServletContextEvent arg0) {

	}

	

}
